﻿
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using WxPayAPI;
using Xfrog.Net;

namespace NB.MGJ.Common
{
    public class WXApi
    {

        //#region 微信普通红包

        ///// <summary>
        ///// 微信普通红包
        ///// </summary>
        ///// <returns></returns>
        //public static JsonObject getCommonRedData()
        //{

        //    string url1 = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";

        //    var parameters1 = new Dictionary<string, string>();

        //    parameters1.Add("key", appkey);//你申请的key

        //    string result1 = sendPost(url1, parameters1, "get");

        //    JsonObject newObj1 = new JsonObject(result1);
        //    String errorCode1 = newObj1["error_code"].Value;

        //    if (errorCode1 == "0")
        //    {
        //        Debug.WriteLine("成功");
        //    }
        //    else
        //    {
        //        //Debug.WriteLine("失败");
        //        Debug.WriteLine(newObj1["error_code"].Value + ":" + newObj1["reason"].Value);
        //    }
        //    return newObj1;
        //}
        //#endregion

        /// <summary>
        /// 发红包接口  公众号方式发送
        /// </summary>
        /// <param name="openid">用户的Openid</param>
        /// <param name="cost">金额</param>
        /// <returns></returns>
 
        //public string SendRedPacket(string openid, decimal cost)
        //{
        //    try
        //    {
        //    string strData = GetJsApiParameters(openid, cost);
        //    string strUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";//这个就是发送红包的API接口了
        //    //string strResult = WxRedPackPost(strUrl, strData);
        //    return strResult;
        //    }
        //    catch (Exception ex)
        //    {
        //        Common.WeiXinHelper.WriteLog("发红包接口err", ex.ToString());
        //        return ex.ToString();
        //    }
        //}

        /// <summary>
        /// 发红包   企业支付到领取  企业支付接口
        /// </summary>
        /// <param name="openid">用户的Openid</param>
        /// <param name="cost">金额</param>
        /// <param name="wxConfigMolde">model 必须有微信号  证书地址 证书密码 appid AppSecret</param>
        /// <returns></returns>
        public bool EnterprisePayUser(string openid, decimal cost, WX_Config wxConfigMolde,string desc,string spbill_create_ip)
        {                                             
            try
            {
                string strData = GetPayUserParameters(openid, cost, wxConfigMolde, desc, spbill_create_ip);
                string strUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";//这个就是发送红包的API接口了
                string mapPath = System.Web.HttpContext.Current.Server.MapPath("~");
                wxConfigMolde.CredentialAddress= mapPath.Substring(0, mapPath.Length - 1) + wxConfigMolde.CredentialAddress;
                WeiXinHelper.WriteLog("证书路径", wxConfigMolde.CredentialAddress);
               // string strResult = WxRedPackPost(strUrl, strData, @"E:\华君君姐姐的Code 胆小者勿入\码管家云系统新框架\NB.MGJ.Web"+wxConfigMolde.CredentialAddress);
                string strResult = WxRedPackPost(strUrl, strData, wxConfigMolde.CredentialAddress,wxConfigMolde.CredentialPwd);

                return true;
            }
              catch (Exception ex)
            {
                Common.WeiXinHelper.WriteLog("EnterprisePayUser企业支付接口err", ex.ToString());
                return false;
            }
        }

     

        /// <summary>
        /// 企业支付用户参数
        /// </summary>
        /// <returns></returns>
        public string GetPayUserParameters(string openid, decimal cost, WX_Config wxConfigMolde, string desc, string spbill_create_ip)
        {
            try
            {
                // wx_config wxConfigMolde = (Session["wxConfig"] as wx_config);
                Random rd = new Random();//构造随机数
                WxPayData jsApiParam = new WxPayData();
                jsApiParam.SetValue("mch_appid", wxConfigMolde.AppId);
                jsApiParam.SetValue("mchid", wxConfigMolde.mchid);
                jsApiParam.SetValue("nonce_str", WxPayApi.GenerateNonceStr());//随机字符串，不长于32位
                jsApiParam.SetValue("partner_trade_no", DateTime.Now.ToString("yyyyMMddHHmmss").ToString());
                jsApiParam.SetValue("openid", openid);
                jsApiParam.SetValue("check_name", "NO_CHECK");////校验用户姓名选项,
                jsApiParam.SetValue("amount", Convert.ToInt32(cost * 100));
                //jsApiParam.SetValue("re_user_name", "dy");//收款人
                jsApiParam.SetValue("desc", desc);
                jsApiParam.SetValue("spbill_create_ip", spbill_create_ip); //Ip地址 
                jsApiParam.SetValue("sign", jsApiParam.MakeSign());//签名,切记，这个签名参数必须放在最后，因为他生成的签名，跟前面的参数有关系
                string parameters = jsApiParam.ToXml();
                return parameters;
            }
            catch (Exception ex)
            {
                Common.WeiXinHelper.WriteLog("企业支付用户err", ex.ToString());
                throw;
            }

        }
        /// <summary>
        /// 提交请求
        /// </summary>
        /// <param name="posturl"></param>
        /// <param name="postData"></param>
        /// <param name="CredentialAddress">证书路径</param>
        /// <param name="CredentialPwd">证书密码</param>
        /// <returns></returns>
        public string WxRedPackPost(string posturl, string postData, string CredentialAddress, string CredentialPwd)
        {
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = Encoding.UTF8;
            byte[] data = encoding.GetBytes(postData);
          
                //CerPath证书路径，这里是本机的路径，实际应用中，按照实际情况来填写
                // string certPath = @"E:\FileTemp\FEIYADONG\tapp\app发布\cert\apiclient_cert.p12";

                //证书密码 
                string password = CredentialPwd;
                //1331562001
                X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(CredentialAddress, CredentialPwd, X509KeyStorageFlags.MachineKeySet);
                // 设置参数  
                request = WebRequest.Create(posturl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;//不可少（个人理解为，返回的时候需要验证）
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                request.ContentType = "text/xml";
                request.ContentLength = data.Length;
                request.ClientCertificates.Add(cert);//添加证书请求
                outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                //发送请求并获取相应回应数据  
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求  
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                //返回结果网页（html）代码  
                string content = sr.ReadToEnd();
                Common.WeiXinHelper.WriteLog("发红包支付信息返回数据", content);
                string err = string.Empty;
                return content;

           
        }
        /**
      * @生成签名，详见签名生成算法
      * @return 签名, sign字段不参加签名
      */
        //public string MakeSign()
        //{
        //    //转url格式
        //    string str = ToUrl();
        //    //在string后加入API KEY
        //    str += "&key=" + WxPayConfig.KEY;
        //    //MD5加密
        //    var md5 = MD5.Create();
        //    var bs = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
        //    var sb = new StringBuilder();
        //    foreach (byte b in bs)
        //    {
        //        sb.Append(b.ToString("x2"));
        //    }
        //    //所有字符转为大写
        //    return sb.ToString().ToUpper();
        //}
        ///**
        //* @Dictionary格式转化成url参数格式
        //* @ return url格式串, 该串不包含sign字段值
        //*/
        //public string ToUrl()
        //{
        //    string buff = "";
        //    foreach (KeyValuePair<string, object> pair in m_values)
        //    {
        //        if (pair.Value == null)
        //        {
        //            Log.Error(this.GetType().ToString(), "WxPayData内部含有值为null的字段!");
        //            throw new WxPayException("WxPayData内部含有值为null的字段!");
        //        }

        //        if (pair.Key != "sign" && pair.Value.ToString() != "")
        //        {
        //            buff += pair.Key + "=" + pair.Value + "&";
        //        }
        //    }
        //    buff = buff.Trim('&');
        //    return buff;
        //}
      
    }
}
